<template>
  <div class="api-test-container">
    <h1>销售订单API测试页面</h1>
    
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <h2>用户登录</h2>
        </div>
      </template>
      <div class="api-section">
        <h3>用户登录</h3>
        <el-form :model="loginForm" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin">登录</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ loginResult }}</pre>
        </div>
      </div>
    </el-card>

    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <h2>销售订单API测试</h2>
        </div>
      </template>
      
      <!-- 创建销售订单 -->
      <div class="api-section">
        <h3>5.1 创建销售订单</h3>
        <el-form :model="createOrderForm" label-width="120px">
          <el-form-item label="地址">
            <el-input v-model="createOrderForm.address" placeholder="请按照'省份 城市 区域 详细地址'格式填写，用空格分隔"></el-input>
            <div class="form-tip">地址格式示例：北京市 海淀区 中关村街道 科技园1号楼</div>
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="createOrderForm.phone" placeholder="请输入电话"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="createOrderForm.remark" type="textarea" placeholder="请输入备注"></el-input>
          </el-form-item>
          
          <div v-for="(item, index) in createOrderForm.items" :key="index" class="order-item">
            <el-divider>商品 {{ index + 1 }}</el-divider>
            <el-form-item label="商品ID">
              <el-input v-model="item.product_id" placeholder="请输入商品ID"></el-input>
            </el-form-item>
            <el-form-item label="数量">
              <el-input-number v-model="item.quantity" :min="1"></el-input-number>
            </el-form-item>
            <el-form-item label="单价">
              <el-input-number v-model="item.unit_price" :precision="2" :step="0.1"></el-input-number>
            </el-form-item>
            <el-form-item label="仓库ID">
              <el-input v-model="item.warehouse_id" placeholder="请输入仓库ID"></el-input>
            </el-form-item>
            <el-button type="danger" @click="removeItem(index)" v-if="createOrderForm.items.length > 1">删除</el-button>
          </div>
          
          <el-button type="primary" @click="addItem">添加商品</el-button>
          <el-form-item>
            <el-button type="primary" @click="handleCreateOrder">创建</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ createOrderResult }}</pre>
        </div>
      </div>
      
      <!-- 获取销售订单列表 -->
      <div class="api-section">
        <h3>5.2 获取销售订单列表</h3>
        <el-form :model="getOrdersForm" label-width="120px">
          <el-form-item label="订单编号">
            <el-input v-model="getOrdersForm.order_number" placeholder="请输入订单编号"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="getOrdersForm.status" placeholder="请选择状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="待付款" value="pending"></el-option>
              <el-option label="已付款" value="paid"></el-option>
              <el-option label="已发货" value="shipped"></el-option>
              <el-option label="已完成" value="completed"></el-option>
              <el-option label="已取消" value="cancelled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker v-model="getOrdersForm.start_date" type="date" placeholder="请选择开始日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker v-model="getOrdersForm.end_date" type="date" placeholder="请选择结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="页码">
            <el-input-number v-model="getOrdersForm.page" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="每页数量">
            <el-input-number v-model="getOrdersForm.limit" :min="1" :max="50"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleGetOrders">获取</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ getOrdersResult }}</pre>
        </div>
      </div>
      
      <!-- 获取销售订单详情 -->
      <div class="api-section">
        <h3>5.3 获取销售订单详情</h3>
        <el-form :model="getOrderDetailForm" label-width="100px">
          <el-form-item label="订单ID">
            <el-input v-model="getOrderDetailForm.id" placeholder="请输入订单ID"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleGetOrderDetail">获取</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ getOrderDetailResult }}</pre>
        </div>
      </div>
      
      <!-- 更新销售订单状态 -->
      <div class="api-section">
        <h3>5.4 更新销售订单状态</h3>
        <el-form :model="updateOrderStatusForm" label-width="120px">
          <el-form-item label="订单ID">
            <el-input v-model="updateOrderStatusForm.id" placeholder="请输入订单ID"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="updateOrderStatusForm.status" placeholder="请选择状态">
              <el-option label="已付款" value="paid"></el-option>
              <el-option label="已发货" value="shipped"></el-option>
              <el-option label="已完成" value="completed"></el-option>
              <el-option label="已取消" value="cancelled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="支付方式" v-if="updateOrderStatusForm.status === 'paid'">
            <el-select v-model="updateOrderStatusForm.payment_method" placeholder="请选择支付方式">
              <el-option label="支付宝" value="alipay"></el-option>
              <el-option label="微信" value="wechat"></el-option>
              <el-option label="现金" value="cash"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="updateOrderStatusForm.note" type="textarea" placeholder="请输入备注"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleUpdateOrderStatus">更新</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ updateOrderStatusResult }}</pre>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 用户登录
const loginForm = reactive({
  username: '',
  password: ''
});
const loginResult = ref('');

const handleLogin = async () => {
  try {
    const response = await axios.post('/api/users/login/', loginForm);
    loginResult.value = JSON.stringify(response.data, null, 2);
    if (response.data.access) {
      localStorage.setItem('token', response.data.access);
      ElMessage.success('登录成功');
    } else {
      ElMessage.error('登录失败: 未获取到token');
    }
  } catch (error) {
    loginResult.value = JSON.stringify(error.response?.data || error.message, null, 2);
    ElMessage.error('登录失败');
  }
};

// 获取token
const getToken = () => {
  return localStorage.getItem('token')
}

// 创建销售订单
const createOrderForm = reactive({
  address: '',
  phone: '',
  remark: '',
  items: [
    {
      product_id: '',
      quantity: 1,
      unit_price: 0,
      warehouse_id: ''
    }
  ]
})
const createOrderResult = ref('')

const addItem = () => {
  createOrderForm.items.push({
    product_id: '',
    quantity: 1,
    unit_price: 0,
    warehouse_id: ''
  })
}

const removeItem = (index) => {
  createOrderForm.items.splice(index, 1)
}

const handleCreateOrder = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    // 验证地址格式
    if (!createOrderForm.address) {
      ElMessage.warning('请输入地址')
      return
    }
    
    // 检查地址格式是否符合要求
    const addressParts = createOrderForm.address.split(' ')
    if (addressParts.length < 3) {
      ElMessage.warning('地址格式不正确，请按照"省份 城市 区域 详细地址"的格式填写，各部分之间用空格分隔')
      return
    }
    
    if (!createOrderForm.phone) {
      ElMessage.warning('请输入电话')
      return
    }
    
    if (createOrderForm.items.length === 0) {
      ElMessage.warning('请添加至少一个商品')
      return
    }
    
    // 验证每个商品的必填字段
    for (const item of createOrderForm.items) {
      if (!item.product_id) {
        ElMessage.warning('请输入商品ID')
        return
      }
      if (!item.warehouse_id) {
        ElMessage.warning('请输入仓库ID')
        return
      }
      if (item.quantity <= 0) {
        ElMessage.warning('商品数量必须大于0')
        return
      }
      if (item.unit_price <= 0) {
        ElMessage.warning('商品单价必须大于0')
        return
      }
    }
    
    // 准备请求数据
    const requestData = {
      address: createOrderForm.address,
      phone: createOrderForm.phone,
      remark: createOrderForm.remark,
      items_data: createOrderForm.items.map(item => ({
        product_id: parseInt(item.product_id),
        quantity: item.quantity,
        unit_price: item.unit_price,
        warehouse_id: parseInt(item.warehouse_id)
      }))
    }
    
    const response = await axios.post(
      '/api/sales-orders/',  // 确保URL末尾有斜杠
      requestData,
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    createOrderResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('订单创建成功')
    
    // 清空表单，方便下次创建
    createOrderForm.address = ''
    createOrderForm.phone = ''
    createOrderForm.remark = ''
    createOrderForm.items = [{
      product_id: '',
      quantity: 1,
      unit_price: 0,
      warehouse_id: ''
    }]
  } catch (error) {
    createOrderResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
    ElMessage.error('订单创建失败')
  }
}

// 获取销售订单列表
const getOrdersForm = reactive({
  order_number: '',
  status: '',
  start_date: '',
  end_date: '',
  page: 1,
  limit: 10
})
const getOrdersResult = ref('')

const handleGetOrders = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const params = {}
    if (getOrdersForm.order_number) params.order_number = getOrdersForm.order_number
    if (getOrdersForm.status) params.status = getOrdersForm.status
    if (getOrdersForm.start_date) params.start_date = getOrdersForm.start_date
    if (getOrdersForm.end_date) params.end_date = getOrdersForm.end_date
    if (getOrdersForm.page) params.page = getOrdersForm.page
    if (getOrdersForm.limit) params.limit = getOrdersForm.limit
    
    const response = await axios.get(
      '/api/sales-orders',
      {
        params,
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    getOrdersResult.value = JSON.stringify(response.data, null, 2)
  } catch (error) {
    getOrdersResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
  }
}

// 获取销售订单详情
const getOrderDetailForm = reactive({
  id: ''
})
const getOrderDetailResult = ref('')

const handleGetOrderDetail = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    if (!getOrderDetailForm.id) {
      ElMessage.warning('请输入订单ID')
      return
    }
    
    const response = await axios.get(
      `/api/sales-orders/${getOrderDetailForm.id}/`,
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    getOrderDetailResult.value = JSON.stringify(response.data, null, 2)
  } catch (error) {
    getOrderDetailResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
  }
}

// 更新销售订单状态
const updateOrderStatusForm = reactive({
  id: '',
  status: '',
  payment_method: '',
  note: ''
})
const updateOrderStatusResult = ref('')

const handleUpdateOrderStatus = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    if (!updateOrderStatusForm.id) {
      ElMessage.warning('请输入订单ID')
      return
    }
    
    if (!updateOrderStatusForm.status) {
      ElMessage.warning('请选择状态')
      return
    }
    
    const data = {
      status: updateOrderStatusForm.status
    }
    
    if (updateOrderStatusForm.status === 'paid' && updateOrderStatusForm.payment_method) {
      data.payment_method = updateOrderStatusForm.payment_method
    }
    
    if (updateOrderStatusForm.note) {
      data.note = updateOrderStatusForm.note
    }
    
    const response = await axios.put(
      `/api/sales-orders/${updateOrderStatusForm.id}/status/`,
      data,
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    updateOrderStatusResult.value = JSON.stringify(response.data, null, 2)
  } catch (error) {
    updateOrderStatusResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
  }
}
</script>

<style scoped>
.api-test-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.api-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.api-section:last-child {
  border-bottom: none;
}

.api-result {
  margin-top: 15px;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
}

.order-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>